// src/views/SensorDashboard.vue
<template>
  <div class="sensor-dashboard">
    <div class="dashboard-header">
      <h1>船舶传感器监控系统</h1>
      <div class="status-bar">
        <span>最后更新: {{ lastUpdate }}</span>
        <span :class="['connection-status', connectionStatus]">
          <el-icon><Connection /></el-icon>
          {{ connectionStatusText }}
        </span>
        <span v-if="loading" class="loading">
          <el-icon class="loading-icon"><Loading /></el-icon>
          数据加载中...
        </span>
      </div>
    </div>

    <div class="sensor-container">
      <!-- 气体传感器组 -->
      <div class="sensor-group">
        <h2>
          <el-icon><Cloudy /></el-icon>气体传感器
        </h2>
        <div class="cards">
          <div
            v-for="(sensor, index) in gasSensors"
            :key="sensor.id"
            class="sensor-card"
            :class="`status-${sensor.status}`"
            @mouseenter="activeIndex = index"
            @mouseleave="activeIndex = -1"
            :style="getCardStyle(index)"
          >
            <div class="card-header">
              <el-icon :size="28"><component :is="sensor.icon" /></el-icon>
              <div class="sensor-info">
                <h3>{{ sensor.name }}</h3>
                <span>{{ sensor.timestamp }}</span>
              </div>
              <div
                class="status-dot"
                :style="{ backgroundColor: statusColors[sensor.status] }"
              ></div>
            </div>
            <div class="card-value">
              <span>{{ sensor.value }}</span>
              <span>{{ sensor.unit }}</span>
            </div>
            <div class="progress">
              <div
                class="progress-bar"
                :style="{
                  width: `${(sensor.value / sensor.max) * 100}%`,
                  backgroundColor: statusColors[sensor.status],
                }"
              ></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 水质传感器组 -->
      <div class="sensor-group">
        <h2>
          <el-icon><Watermelon /></el-icon>水质传感器
        </h2>
        <div class="cards">
          <div
            v-for="(sensor, index) in waterSensors"
            :key="sensor.id"
            class="sensor-card"
            :class="`status-${sensor.status}`"
            @mouseenter="activeIndex = gasSensors.length + index"
            @mouseleave="activeIndex = -1"
            :style="getCardStyle(gasSensors.length + index)"
          >
            <div class="card-header">
              <el-icon :size="28"><component :is="sensor.icon" /></el-icon>
              <div class="sensor-info">
                <h3>{{ sensor.name }}</h3>
                <span>{{ sensor.timestamp }}</span>
              </div>
              <div
                class="status-dot"
                :style="{ backgroundColor: statusColors[sensor.status] }"
              ></div>
            </div>
            <div class="card-value">
              <span>{{ sensor.value }}</span>
              <span>{{ sensor.unit }}</span>
            </div>
            <div class="progress">
              <div
                class="progress-bar"
                :style="{
                  width: `${(sensor.value / sensor.max) * 100}%`,
                  backgroundColor: statusColors[sensor.status],
                }"
              ></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
  Cloudy,
  Watermelon,
  Position,
  Warning,
  Sunset,
  Connection,
  Lightning,
  Loading,
} from "@element-plus/icons-vue";

// 状态管理
const activeIndex = ref(-1);
const lastUpdate = ref("--");
const loading = ref(false);
const connectionStatus = ref("connected");
const specialMode = ref(false);
const specialModeStartTime = ref(0);
const specialModePhase = ref(0); // 0:初始 1:变橙色 2:恢复正常 3:变红色

// 传感器配置（包含模拟参数）
const sensorConfig = [
  // 气体传感器
  {
    id: 1,
    type: "gas",
    name: "烟雾浓度",
    unit: "ppm",
    icon: Cloudy,
    base: 72,
    fluctuation: 2,
    max: 500,
  },
  {
    id: 2,
    type: "gas",
    name: "乙醇浓度",
    unit: "ppm",
    icon: Warning,
    base: 2.5,
    fluctuation: 0.1,
    max: 10,
  },
  {
    id: 3,
    type: "gas",
    name: "一氧化碳",
    unit: "ppm",
    icon: Cloudy,
    base: 16.5,
    fluctuation: 0.5,
    max: 20,
  },
  {
    id: 4,
    type: "gas",
    name: "可燃气体",
    unit: "ppm",
    icon: Sunset,
    base: 3.5,
    fluctuation: 0.1,
    max: 10,
  },

  // 水质传感器
  {
    id: 5,
    type: "water",
    name: "PH值",
    unit: "",
    icon: Watermelon,
    base: 6.3,
    fluctuation: 0.1,
    max: 14,
  },
  {
    id: 6,
    type: "water",
    name: "电导率",
    unit: "μS/cm",
    icon: Lightning,
    base: 600,  // 正常基准值
    warningValue: 750, // 橙色警告值(75% of max)
    dangerValue: 850,  // 红色危险值(85% of max)
    max: 900,
    fluctuation: 5,
  },
  {
    id: 7,
    type: "water",
    name: "水温",
    unit: "°C",
    icon: Watermelon,
    base: 25.0,
    fluctuation: 0.2,
  },
  { id: 8, type: "water", name: "液位", unit: "米", icon: Position, base: 0 },
  {
    id: 9,
    type: "water",
    name: "浊度",
    unit: "NTU",
    icon: Cloudy,
    base: 38,   // 正常基准值
    warningValue: 50.5, // 橙色警告值(75% of max)
    dangerValue: 60,  // 红色危险值(85% of max)
    max: 60,
    fluctuation: 1,
  },
  { id: 10, type: "water", name: "取水样", unit: "%", icon: Position, base: 0 },
  { id: 11, type: "water", name: "光电效率", unit: "%", base: 80 ,fluctuation: 1},
];

// 初始化传感器数据
const sensors = ref(
  sensorConfig.map((config) => ({
    ...config,
    value: config.base,
    status: "normal",
    timestamp: new Date().toLocaleTimeString(),
    lastValue: config.base,
  }))
);

// 状态颜色映射
const statusColors = {
  normal: "#67c23a",
  warning: "#e6a23c",
  danger: "#f56c6c",
  unknown: "#909399",
};

// 计算属性
const gasSensors = computed(() =>
  sensors.value.filter((s) => s.type === "gas")
);
const waterSensors = computed(() =>
  sensors.value.filter((s) => s.type === "water")
);
const connectionStatusText = computed(
  () =>
    ({
      connected: "连接正常",
      disconnected: "连接断开",
      error: "连接异常",
    }[connectionStatus.value])
);

// 方法定义
const getCardStyle = (index) => ({
  transform:
    activeIndex.value === index ? "translateY(-5px) scale(1.02)" : "none",
  zIndex: activeIndex.value === index ? 10 : 1,
});

const updateSensorStatus = (sensor, newValue) => {
  const ratio = (newValue / sensor.max) * 100;
  return ratio >= 85 ? "danger" : ratio >= 75 ? "warning" : "normal";
};

// // 生成带波动的随机值
// const generateFluctuatedValue = (sensor) => {
//   const fluctuation = sensor.fluctuation || 0;
//   const base = sensor.base || 0;
//   const value = base + (Math.random() * 2 - 1) * fluctuation;
//   return Number(Math.max(0, value).toFixed(2));
// };
const generateFluctuatedValue = (sensor) => {
  return sensor.base; // 直接返回基准值，去除随机波动 
};

// 计算特殊模式下的值
const calculateSpecialValue = (sensor, elapsedTime) => {
  // 第一阶段：10秒内从基准值上升到橙色警告值
  if (elapsedTime <= 10000) {
    const progress = elapsedTime / 10000;
    return sensor.base + (sensor.warningValue - sensor.base) * progress;
  }
  // 第二阶段：5秒内从橙色警告值恢复到基准值
  else if (elapsedTime <= 15000) {
    const progress = (elapsedTime - 10000) / 5000;
    return sensor.warningValue - (sensor.warningValue - sensor.base) * progress;
  }
  // 第三阶段：8秒内从基准值突变到红色危险值
  else if (elapsedTime <= 23000) {
    const progress = (elapsedTime - 15000) / 8000;
    return sensor.base + (sensor.dangerValue - sensor.base) * progress;
  }
  // 保持红色危险值
  else {
    return sensor.dangerValue;
  }
};

const fetchSensorData = async () => {
  try {
    loading.value = true;

    // 随机触发特殊模式（仅当不在特殊模式中时）
    if (!specialMode.value && Math.random() < 0.05) {
      specialMode.value = true;
      specialModeStartTime.value = Date.now();
      specialModePhase.value = 1;
      console.log("进入特殊模式 - 第一阶段：变橙色");
    }

    const currentTime = Date.now();
    let elapsedTime = 0;
    
    if (specialMode.value) {
      elapsedTime = currentTime - specialModeStartTime.value;
      
      // 检查是否需要切换到下一阶段
      if (elapsedTime > 10000 && specialModePhase.value === 1) {
        specialModePhase.value = 2;
        console.log("进入第二阶段：恢复正常");
      } else if (elapsedTime > 15000 && specialModePhase.value === 2) {
        specialModePhase.value = 3;
        console.log("进入第三阶段：变红色");
      } else if (elapsedTime > 23000 && specialModePhase.value === 3) {
        specialMode.value = false;
        console.log("特殊模式结束");
      }
    }

    // 更新传感器数据
    sensors.value = sensors.value.map((sensor) => {
      let newValue;
      
      // 电导率(id=6)和浊度(id=9)在特殊模式下
      if (specialMode.value && (sensor.id === 6 || sensor.id === 9)) {
        newValue = calculateSpecialValue(sensor, elapsedTime);
      } else {
        newValue = generateFluctuatedValue(sensor);
      }

      return {
        ...sensor,
        value: Number(newValue.toFixed(2)),
        status: updateSensorStatus(sensor, newValue),
        lastValue: sensor.value,
        timestamp: new Date().toLocaleTimeString(),
      };
    });

    lastUpdate.value = new Date().toLocaleTimeString();
    connectionStatus.value = "connected";
  } catch (error) {
    console.error("数据模拟失败:", error);
    connectionStatus.value = "error";
    ElMessage.error("数据模拟失败: " + error.message);
  } finally {
    loading.value = false;
  }
};

// 初始化
onMounted(() => {
  fetchSensorData();
  //const timer = setInterval(fetchSensorData, 1000); // 1秒更新一次
  return () => clearInterval(timer);
});
</script>


<style scoped>
.sensor-dashboard {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.dashboard-header {
  margin-bottom: 24px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.dashboard-header h1 {
  margin: 0;
  color: #303133;
  font-size: 24px;
}

.status-bar {
  display: flex;
  gap: 20px;
  align-items: center;
  margin-top: 12px;
  color: #606266;
  font-size: 14px;
}

.connection-status {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 4px 8px;
  border-radius: 4px;
}

.connection-status.connected {
  background: #f0f9eb;
  color: #67c23a;
}

.connection-status.disconnected {
  background: #fdf6ec;
  color: #e6a23c;
}

.connection-status.error {
  background: #fef0f0;
  color: #f56c6c;
}

.loading {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #909399;
}

.loading-icon {
  animation: rotate 2s linear infinite;
}

.sensor-container {
  display: grid;
  gap: 24px;
}

.sensor-group {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.sensor-group h2 {
  margin: 0 0 16px 0;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #303133;
  font-size: 20px;
}

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.sensor-card {
  padding: 16px;
  border-radius: 8px;
  background: white;
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  border-left: 4px solid;
}

.sensor-card.status-normal {
  border-left-color: #67c23a;
}

.sensor-card.status-warning {
  border-left-color: #e6a23c;
}

.sensor-card.status-danger {
  border-left-color: #f56c6c;
}

.sensor-card.status-unknown {
  border-left-color: #909399;
}

.card-header {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 12px;
}

.sensor-info {
  flex: 1;
}

.sensor-info h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.sensor-info span {
  font-size: 12px;
  color: #909399;
}

.status-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
}

.card-value {
  display: flex;
  align-items: baseline;
  gap: 4px;
  margin-bottom: 8px;
}

.card-value span:first-child {
  font-size: 24px;
  font-weight: 500;
  color: #303133;
}

.card-value span:last-child {
  font-size: 14px;
  color: #909399;
}

.progress {
  height: 6px;
  background: #ebeef5;
  border-radius: 3px;
  overflow: hidden;
}

.progress-bar {
  height: 100%;
  transition: width 0.5s ease;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>